Advertisement
Guest User

Untitled

a guest
Mar 4th, 2018
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.13 KB | None | 0 0
  1. #define F_CPU 8000000UL
  2. #include <avr/io.h>
  3.  
  4. #define KPAD_PORT   PORTD
  5. #define KPAD_DDR    DDRD
  6. #define KPAD_PIN    PIND
  7.  
  8. /*
  9. Column  PD0 - PD3
  10. Rows    PD4 - PD7            
  11.              _____
  12.         PC6 |     | pc5 (SCL)
  13.   C0 -  PD0 |     | pc4 (SDA)
  14.   C1 -  PD1 |     | pc3
  15.   C2 -  PD2 |     | pc2 (ADC2)
  16.   C3 -  PD3 |     | pc1 (ADC1)
  17.   R0 -  PD4 |     | pc0 (ADC0)
  18.         VCC |     | GND
  19.         GND |     | AREF  
  20.         PB6 |     | AVCC  
  21.         PB7 |     | PB5 (SCK)
  22.   R2 -  PD5 |     | PB4 (MISO)
  23.   R3 -  PD6 |     | PB3 (MOSI)
  24.   R4 -  PD7 |     | PB2 (SS)
  25.         PB0 |_____| PB1
  26.  
  27.  
  28.     Function return the key code when a key is pressed
  29.     Keys are numbered as follows
  30.     @param: None
  31.     [01] [02] [03] [A]
  32.     [04] [05] [06] [B]
  33.     [07] [08] [09] [C]
  34.     [*]  [0]  [#]  [D]
  35.     Return 255 if none of the keys are pressed.
  36. */
  37.  
  38.  
  39. uint8_t KeyPressed() {
  40.     uint8_t row, colum;
  41.    
  42.     // The column C0 to C4 are kept at High Z State, these pins are not high or low, they are tristate. (inputs)
  43.     // And their port value is set as low as well.
  44.     // When the ddr (N)bit changes to 1, the port become output with value low.
  45.    
  46.     // 11110000
  47.     // Enable pull-ups on the column's
  48.     KPAD_PORT |= 0Xf0;
  49.    
  50.     for(colum=0; colum<4; colum++)
  51.     {
  52.         // Make all the pins inputs. (0)'s
  53.         // The column inputs will have pullups as defined in KPAD_PORT
  54.         KPAD_DDR &= ~(0Xff);
  55.         _delay_ms(2);
  56.  
  57.         // Go though the colum's
  58.         // Set the Column pin from High Z state to a output.
  59.         // c=0       c=1       c=2       c=3
  60.         // 1000nnnn, 0100nnnn, 0010nnnn, 0001nnnn
  61.         KPAD_DDR |= (0X80>>colum);
  62.         _delay_ms(2);
  63.        
  64.         for(row=0; row<4; row++)
  65.         {
  66.             // Go though each row.
  67.             // r=0       r=1       r=2       r=3
  68.             // nnnn1000, nnnn0100, nnnn0010, nnnn0001
  69.             uint8_t pinvalue = KPAD_PIN & (0X08>>row);
  70.             if(!(pinvalue))
  71.             {
  72.                 // Return the button pressed!.
  73.                 return (row*4+colum);
  74.             }
  75.         }
  76.     }
  77.     return 0Xff;
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement